import time
import re

from settings import LTC_BOT_NAME, AD_MESSAGE, MAX_FAILURES, ACTIVATE_SENDING_MESSAGE, DELAY_BETWEEN_SESSIONS, \
    STANDART_DELAY

from Console import console
from Client import create_clients
from proxy import  Proxy_controller, get_all_proxys
from automatization import add_clicking, send_to_bots, add_to_the_group, leave_all_old_groups, begin
import asyncio
from telethon.tl.functions.channels import JoinChannelRequest, LeaveChannelRequest
from random import randint
from balance import check_balance


async def work_with_one(client, Proxy = None, BOT_NAME=LTC_BOT_NAME):
    if Proxy:
        client.set_proxy(Proxy.telethon_proxy())

    http_prx = Proxy.selenium_proxy() if Proxy else None
    if http_prx:
        console.send_notification("Using http proxy: {}".format(http_prx))


    await client.start()

    dialogs = await client.get_dialogs()
    bot_chat = None
    for dlg in dialogs:

        if dlg.title == BOT_NAME:
            bot_chat = dlg

    if not bot_chat:
        console.send_alert("No chat was found for {}, finishing for account {}".format(BOT_NAME, client.api_id))
        client.disconnect()
        return

    await begin(client, BOT_NAME)
    console.send_notification("Leaving old channels")
    await leave_all_old_groups(client)
    console.send_notification("Working with adds")
    await add_clicking(client, bot_chat, BOT_NAME, http_prx)
    console.send_notification("Working with bots")
    await send_to_bots(client, bot_chat, BOT_NAME, http_prx)
    console.send_notification("Working with channels and groups")
    await add_to_the_group(client, bot_chat, BOT_NAME, http_prx)
    await client.disconnect()


async def main_process():
    pos = 0

    clients = create_clients()
    console.debug("Working with {} accounts".format(len(clients)))

    if len(clients) == 0:
        console.send_critical("Add accounts first")
        raise IndexError

    end = len(clients)
    Controller = Proxy_controller(get_all_proxys())
    while True:

        client = clients[pos]

        end = len(clients)
        await work_with_one(client, Proxy=Controller.get_proxy())
        # after exiting from previous account:
        pos += 1
        if pos == end:
            pos = 0
            delay = randint(DELAY_BETWEEN_SESSIONS[0], DELAY_BETWEEN_SESSIONS[1])
            console.send_notification("Sleeping for {} minutes".format(delay))
            await check_balance()
            time.sleep(delay * 60)

        console.send_notification("Switching to next account")


if __name__ == '__main__':
    while True:
        try:
            asyncio.run(main_process())
        except IndexError:
            break
        except Exception as e:
            console.send_critical("Error occured in main process: {}".format(e))

